<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单的模板引擎</title>
</head>
<body>
    <div id="app"></div>
    <template id="tpl">
        <div>你{{}} 好</div>
        <div>{{name}},年龄：{{age}}</div>
        <br/>
        <div>学院信息:{ 名称：{{
            school.name 
        }} }</div>
    </template>
    <script>
        let template = function(tpl,d){
            // 匹配html标签
            // const propNameRegexp = /([a-zA-Z_$][a-zA-Z0-9_$]*)/g;
            const search = (str, reg, flags) => {
                let result = [], match;
                flags = flags || ''
                const regex = new RegExp(reg, `g${flags}`)
                while(match = regex.exec(str)){
                    match.forEach((item, i) => {
                        i > 0 && item && result.push(item);
                    })
                }
                return result;
            }
            return tpl.replace(/\{\{([^\}]*?)\}\}/g,(allContent, ...args) => { //allContent: 是replace正则匹配的所有内容
                const props = search(args[0], /([a-zA-Z_$][a-zA-Z0-9_$]*)|\[(\d)\]/);
                const propsExpr = props.reduce((propsExpr, prop)=> propsExpr += '["'+prop+'"]', '')
                return eval('propsExpr.length > 0 ? d'+propsExpr+' : args[0]')
            })
        }
        const tpl = document.querySelector('#tpl')
        document.querySelector('#app').innerHTML = template(tpl.innerHTML,{name:'ck',age:18,school:{name:'国防科技'}});
    </script>
</body>
</html>